var express = require('express');
const {userModel}=require('../model/userModel')
//导入jsonwebtoken
const jwt=require('jsonwebtoken')
var router = express.Router();
router.get('/userList', async function(req, res, next) {
   const rows=await userModel.find()
   res.send({
     code:1,
     rows:rows
   })
});
router.post('/addUser',async(req,res)=>{
  let user={
    username:req.body.username,
    password:req.body.password,
    phone:req.body.phone,
    desc:req.body.desc,
    gender:req.body.gender,
    avatar:req.body.avatar,
    age:~~req.body.age,
    birthday:new Date(req.body.birthday),
  }
  try{
    const result=await userModel.create(user)
    if(result){
      res.send({
        code:1,
        message:'增加成功'
      })
    }
  }catch(err){
     res.send({
       code:0,
       message:'增加失败'
     })
  }
})

router.delete('/delUser/:_id',async(req,res)=>{
  const {deletedCount}=await userModel.deleteOne({_id:req.params._id})
  if(deletedCount){
    res.send({
      code:1,
      message:'删除成功'
    })
  }
})

/* 用户登录 */
router.post('/login',(req,res)=>{
  const result=userModel.findOne(req.body)
  if(result){
    /*
       生成jwt的token令牌,sign有三个参数
       参数1：有效载荷信息
       参数2：密钥
       参数3：token的失效时间
    */
    let token=jwt.sign({username:result.username},"gileskey",{expiresIn:'1h'})
    res.send({
      code:1,
      message:'用户登录成功',
      token:'Bearer '+token
    })
  }else{
    res.send({
      code:0,
      message:'登录失败'
    })
  }
})

module.exports = router;
